const secret = "jiubei_0128";
const jwt = require("jsonwebtoken");

const { tags } = require("../config/config.default");

//!封装一个验证token的中间件
const auth = async (ctx, next) => {
  console.log("打印tags如下：", tags);
  let { "x-access-token": access_token, "x-refresh-token": refresh_token } =
    ctx.request.headers;
  access_token = access_token.substring(1, access_token.length - 1);
  refresh_token = refresh_token.substring(1, refresh_token.length - 1);
  jwt.verify(access_token, secret, (err, decoded) => {
    if (err) {
      // token无效或已过期
      console.log("access_token无效或已过期");
      console.log(err);
      return false;
    } else {
      // 解密后的token信息可通过decoded获取
      console.log("access_token解密成功!信息如下：");
      console.log(decoded);
      return decoded;
    }
  });
  jwt.verify(refresh_token, secret, (err, decoded) => {
    if (err) {
      // token无效或已过期
      console.log("refresh_token无效或已过期");
      console.log(err);
      return false;
    } else {
      // 解密后的token信息可通过decoded获取
      console.log("refresh_token解密成功!信息如下：");
      console.log(decoded);
      return decoded;
    }
  });
  await next();
};

module.exports = auth;
